ASP.NET Core

Create Razor Pages with ASP.NET Core.

ASP.NET Core

ASP.NET Core is a cross-platform framework for building Internet-connected apps.

Razor Pages is the preferred way to create page or form-based apps in ASP.NET Core. From the docs, "Razor Pages can make coding page-focused scenarios easier and more productive than using controllers and views."

I used Visual Studio 2022 and ASP.NET Core to create a todo app.

I clicked the Create a new project button.

I selected the ASP.NET Core Web Site option

I accepted the default solution/project name

I selected the .NET 6.0 framework

The template project was downloaded

Page and PageModel

Razor pages include HTML markup and are similar to MVC views.

Razor PageModel classes are combination of MVC controllers and models. 

The OnGet() method below is executed when a browser sends a GET request to the server.

An OnPost() method is executed when a browser sends a POST request to the server.

I updated the PageModel to include a message property set in the OnGet() method

I updated the corresponding Razor page to include the Message.

I tested the Web application

I created a Data folder to hold classes generated by Entity framework.

I wanted Entity framework to generate the classes needed to access and update the contents of a todo items database.

I installed the dotnet-ef (entity framework) tool

I needed to add a references to the Microsoft.EntityFrameworkCore.Design and Microsoft.EntityFrameworkCore.SqlServer packages.

I ran the dotnet ef dbcontext scaffold... command to generate the entity framework related classes.

The Item class describes a database table row.

I created a ToDo folder in the Pages folder.

I right clicked on the ToDo folder and selected the Add | New Scaffolded Item... menu item

I selected the Entity framework classes I generated eariler.

I watched the progress bar

I ran into an odd issue related to the Microsoft.VisualStudio.Web.CodeGeneration.Design package that was already installed. I reinstalled and tried again.

The CRUD Razor pages were generated.

I updated Program.cs to include a reference to ToDoContext...

...and ran the Web app by navigating to /ToDo

I used the create page to create a ToDo item.

The create page's OnPostAsync() method added the new item (using entity framework) and redirected me back to the ToDo index page.

I updated the appsettings.json file to include the database connection string.

I updated Program.cs to include a reference to the appsettings value.

I updated the ToDoContext class's OnModelCreating() method (removing the hardcoded connection string).